// Class A: ST
giveme ST, clear nofin
sort stkcd accper
generate FD_a = ST == 1
by stkcd: generate iFD_a = ST & !ST[_n-1]
by stkcd: generate preFD_a = iFD_a[_n+1] == 1 | iFD_a[_n+2] == 1
keep stkcd accper FD_a iFD_a preFD_a
savemy tmp FD_a

// Class B: MV & ICR
giveme Size, clear nofin
giveme final MV, merge id(stkcd) t(accper) keep(1 3)
giveme final ICRebitda, merge id(stkcd) t(accper) keep(1 3)
giveme final ICRocf, merge id(stkcd) t(accper) keep(1 3)
sort stkcd accper
by stkcd: generate MVdown = MV < MV[_n-1]
by stkcd: generate IElow = ICRebitda < 2
by stkcd: generate IOlow = ICRocf < 1
by stkcd: generate C1 = MVdown == 1 & MVdown[_n-1] == 1
by stkcd: generate C2 = IElow == 1 & IElow[_n-1] == 1
by stkcd: generate C3 = IOlow == 1 & IOlow[_n-1] == 1
generate FD_b = C1 == 1 & C2 == 1 & C3 == 1
by stkcd: generate iFD_b = FD_b == 1 & FD_b[_n-1] == 0
by stkcd: generate preFD_b = iFD_b[_n+1] == 1 | iFD_b[_n+2] == 1
keep stkcd accper FD_b iFD_b preFD_b
savemy tmp FD_b

// Class C: Quick, Current and ROA
giveme Size indcd, clear nofin
giveme final Quick, merge id(stkcd) t(accper) keep(1 3)
giveme final Current, merge id(stkcd) t(accper) keep(1 3)
giveme final ROA, merge id(stkcd) t(accper) keep(1 3)
sort accper indcd Quick
by accper indcd: generate lowQ = _n < _N * 0.1
sort accper indcd Current
by accper indcd: generate lowC = _n < _N * 0.1
sort accper indcd ROA
by accper indcd: generate lowR = _n < _N * 0.1
sort stkcd accper
generate FD_c = lowQ == 1 & lowC == 1 & lowR == 1
by stkcd: generate iFD_c = FD_c == 1 & FD_c[_n-1] == 0
by stkcd: generate preFD_c = iFD_c[_n+1] == 1 | iFD_c[_n+2] == 1
keep stkcd accper FD_c iFD_c preFD_c
savemy tmp FD_c

// Class D: annual return
giveme annualret, clear nofin
sort stkcd accper
generate FD_d = annualret < -0.6
by stkcd: generate iFD_d = annualret < -0.6 & annualret[_n-1] >= -0.6
by stkcd: generate preFD_d = iFD_d[_n+1] == 1 | iFD_d[_n+2] == 1
keep stkcd accper FD_d iFD_d preFD_d
savemy tmp FD_d

// Class E: Z score
giveme Size, clear nofin start(2000)
giveme final Zscore, merge id(stkcd) t(accper) keep(1 3)
generate FD_e = Zscore < 1.81
sort stkcd accper
by stkcd: generate iFD_e = FD_e == 1 & FD_e[_n-1] == 0
by stkcd: generate preFD_e = iFD_e[_n+1] == 1 | iFD_e[_n+2] == 1
keep stkcd accper FD_e iFD_e preFD_e
savemy tmp FD_e

// Merge
giveme Size, clear nofin start(2007)
giveme tmp FD_a, merge on(stkcd accper) keep(1 3)
giveme tmp FD_b, merge on(stkcd accper) keep(1 3)
giveme tmp FD_c, merge on(stkcd accper) keep(1 3)
giveme tmp FD_d, merge on(stkcd accper) keep(1 3)
giveme tmp FD_e, merge on(stkcd accper) keep(1 3)
foreach i in a b c d e {
    drop if FD_`i' == .
    drop if iFD_`i' == .
    drop if preFD_`i' == .
}
savemy tmp fd_all

